#!/usr/bin/env python
# encoding: utf-8

import sys
import os
from MeshToolKit.mesh_node import *
from MeshToolKit.mesh_entry import *
from MeshToolKit.mesh import *

def main(mesh_filename, des_filename):
	m = mesh(mesh_filename=mesh_filename, des_filename=des_filename)
	try :
		while 1:
			term=''
			try :
				term=raw_input('> ')
			except :
				raise
			node = m.lookup_id(term)
			if node:
				print_mesh_node_details(node)
				continue
			nodes = m.lookup_name(term)
			if nodes:
				print "These mesh entries match the given name:"
				for node in nodes:
					print_mesh_node_details(node)
				continue
			nodes = m.lookup_entry_term(term)
			if nodes:
				print "These mesh entries match the given name:"
				for node in nodes:
					print_mesh_node_details(node)
				continue
			terms = m.get_approximate_terms(term)
			if terms:
				print "Could not find the term you were looking for, did you mean:"
				print " , ".join(terms)
				continue
			print "Could not find the term you were looking for"
	except KeyboardInterrupt:
		return

def print_mesh_node_details(node):
	"""Prints name, id etc"""
	if node.parent.id == None:
		parent = '<no parent>'
	else:
		parent = node.parent
		
	print "Details for the node", node.name
	print "ID:", node.id, "\nName:", node.name, "\nParent:", parent, "\nChildren:", [child.id for child in node.children], "\nDescription:", node.entry.description
	
if __name__ == '__main__':
	if len(sys.argv) !=3:
		print "Requires a mesh mtrees filename (generally called mtrees2007.bin) and description filename (generally called d2007.bin)"
	else:
		main(sys.argv[1], sys.argv[2])